<template>
  <div ref="chartRef" style="width: 100%; height: 100%"></div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { ElMessage } from "element-plus";
import { getCategoryPieData } from "@/api/index";


const chartRef = ref(null);
let chart = null;

const initChart = () => {
  const option = {
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        name: "图书分类",
        type: "pie",
        radius: "50%",
        data: [],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  chart.setOption(option);
};

//获取后端数据
const getData = async () => {
  try {
    const response = await getCategoryPieData();
    if (!response || !response.data) {
      throw new Error('数据获取失败');
    }
    const data = response.data;
    // 更新图表配置
    chart.setOption({
      series: [{
        data: data.map(item => ({
          value: item.value,
          name: item.name
        }))
      }]
    });
  } catch (error) {
    console.error("获取数据失败:", error);
    // 可以在这里添加错误提示，比如使用 ElMessage
    ElMessage.error('获取图表数据失败');
  }
};

onMounted(() => {
  chart = echarts.init(chartRef.value);
  initChart();
  // 获取实际数据
  getData();

  // 添加窗口大小变化监听
  window.addEventListener("resize", () => {
    chart?.resize();
  });
});
</script>
